package com.bitk.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class CustomDecisionManager implements AccessDecisionManager {

    /**
     * 分析访问URL所需的角色,查看请求用户是否具备?
     * 如果不具备,就抛出AccessDeniedException异常,否则do nothing
     * @param authentication 用户所具有的角色
     * @param object 保护对象,在这里是FilterInvocatin对象.在他里面可以访问到请求的URL
     * @param configAttributes configAttributes.getAttributes()中保存了请求当前所需要的权限角色
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

        for (ConfigAttribute configAttribute : configAttributes) {
            String needRole = configAttribute.getAttribute();
            //处理只要登录权限的用户请求.
            if("ROLE_LOGIN".equals(needRole)){
                if (authentication instanceof AnonymousAuthenticationToken)
                    throw new AccessDeniedException("尚未登录,请登录");
                return;
            }

            //如果有一项权限通过了,AccessDecisionManager就同意访问
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); //用户所具有的权限
            for (GrantedAuthority authority : authorities) {
                System.err.println(this.getClass().getName()+"---访问["+ ((FilterInvocation) object).getRequestUrl()+"需要的权限是["+needRole);
                System.err.println(this.getClass().getName()+"---当前用户所具有的权限是:"+authority.getAuthority().toString());
                if(authority.getAuthority().equals(needRole))//对比权限
                    return;
            }
        }
        throw new AccessDeniedException("对不起,您的权限不足.");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
